<template>
  <div class="videoAdManagement">
    <h3>广告管理</h3>
    <div class="opration">
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="addData"
        v-if="permissions_obj.id_110||permissions_obj.id_all"
      >添加</el-button>
      <!-- <el-button type="danger" icon="el-icon-delete" @click="batchDelete">批量删除</el-button> -->
    </div>
    <div class="list">
      <el-table
        border
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column type="index" width="50" header-align="center" align="center" label="序号"></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="id"
          label="ID"
          sortable
          width="90"
        ></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="type_text"
          label="封面类型"
          width="100"
        ></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="position_text"
          label="广告位置"
          width="100"
        ></el-table-column>
        <el-table-column header-align="center" align="center" prop="num" label="图片" width="200">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.cover"
              :preview-src-list="scope.row.srcList"
              fit="“cover”"
            ></el-image>
            <div v-if="scope.row.type==2">
              <el-button size="mini" type="primary" @click="handlePlay(scope.$index, scope.row)">播放</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" prop="title" label="标题" width="180"></el-table-column>
        <el-table-column header-align="center" align="center" prop="category" label="跳转类型"></el-table-column>
        <el-table-column header-align="center" align="center" prop="link" label="跳转链接"></el-table-column>
        <el-table-column header-align="center" align="center" label="开关" width="80">
          <template slot-scope="scope">
            <div  v-if="scope.row.status==2">转码中</div>
            <div  v-if="scope.row.status==3">转码失败</div>
            <div v-if="scope.row.status==0||scope.row.status==1">
              <el-switch
                v-model="scope.row.status"
                @change="changeSwitch(scope.$index, scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                v-if="permissions_obj.id_5||permissions_obj.id_all"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" prop="sort" label="排序" width="80"></el-table-column>
        <el-table-column header-align="center" align="center" label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="permissions_obj.id_110||permissions_obj.id_all"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="permissions_obj.id_6||permissions_obj.id_all"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage1"
        :page-sizes="[10,30,50,100]"
        :page-size="pageSize"
        layout="total, prev, pager, next,sizes,jumper"
        :total="totalSize"
      ></el-pagination>
    </div>
    <!-- //修改广告信息弹窗 -->
    <el-dialog title="广告详情" :visible.sync="modifyEditorDialogVisible" width="40%" center>
      <div class="row">
        <span>ID：</span>
        <el-input v-model="inputID" placeholder :disabled="true"></el-input>
      </div>
      <div class="row">
        <span>封面类型：</span>
        <font>{{inputAdType_text}}</font>
      </div>
      <div class="row">
        <span>广告位置：</span>
        <font>{{inputPosition_text}}</font>
      </div>
      <div class="row">
        <span>广告标题：</span>
        <el-input v-model="inputAdTitle" placeholder="请输入广告标题" clearable></el-input>
      </div>
      <div class="row">
        <span>上传图片：</span>
        <el-upload
          :action="imgUploadParth"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :limit="1"
          :on-success="imgUploadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </div>
      <div class="row" v-if="inputAdType=='2'">
        <span>视频文件：</span>
        <el-upload
          class="upload-demo"
          list-type="picture"
          :action="vedioUploadParth"
          :limit="1"
          :on-success="uploadSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <!-- <div class="row">
        <span>时间：</span>
        <el-date-picker
          v-model="inputTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </div> -->
      <div class="row">
        <span>跳转类型：</span>
        <el-select v-model="inputJumpType" placeholder="请选择">
          <el-option
            v-for="item in optionsLinkType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="row">
        <span>跳转链接：</span>
        <el-input v-model="inputJumpLink" placeholder="请输入跳转链接" clearable></el-input>
      </div>
      <div class="row">
        <span>排序：</span>
        <el-input-number v-model="inputSort" :min="1"></el-input-number>
      </div>
      <div class="dialogBtn">
        <el-button type="primary" size="small" @click="submitModifyEditor">提交</el-button>
        <el-button type="info" size="small" @click="cancelModifyEditor">取消</el-button>
      </div>
    </el-dialog>
    <!-- //添加广告信息弹窗 -->
    <el-dialog title="添加广告" :visible.sync="addAdDialogVisible" width="40%" center>
      <div class="row">
        <span>封面类型：</span>
        <el-select v-model="inputAdType" placeholder="请选择">
          <el-option
            v-for="item in optionsAdType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="row">
        <span>广告位置：</span>
        <el-select v-model="inputPosition" placeholder="请选择">
          <el-option
            v-for="item in optionsPosition"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="row">
        <span>广告标题：</span>
        <el-input v-model="inputAdTitle" placeholder="请输入广告标题" clearable></el-input>
      </div>
      <div class="row">
        <span>上传图片：</span>
        <el-upload
          :action="imgUploadParth"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :limit="1"
          :on-success="imgUploadSuccess"
          :file-list="fileList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </div>
      <div class="row" v-if="inputAdType=='2'">
        <span>视频文件：</span>
        <el-upload
          class="upload-demo"
          list-type="picture"
          :action="vedioUploadParth"
          :limit="1"
          :on-success="uploadSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <!-- <div class="row">
        <span>时间：</span>
        <el-date-picker
          v-model="inputTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </div> -->
      <div class="row">
        <span>跳转类型：</span>
        <el-select v-model="inputJumpType" placeholder="请选择">
          <el-option
            v-for="item in optionsLinkType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="row">
        <span>链接/视频id：</span>
        <el-input v-model="inputJumpLink" placeholder="会员/钻石充值中心可不填" clearable></el-input>
      </div>
      <div class="row">
        <span>排序：</span>
        <el-input-number v-model="inputSort" :min="1"></el-input-number>
      </div>
      <div class="dialogBtn">
        <el-button type="primary" size="small" @click="submitAdd">提交</el-button>
        <el-button type="info" size="small" @click="cancelAdd">取消</el-button>
      </div>
    </el-dialog>
    <!-- //播放弹窗 -->
    <el-dialog title="播放" :visible.sync="playDialogVisible" width="40%" center>
      <div>
        <video
          controls
          width="100%"
          height="500"
          :src="playUrl"
        >Sorry, your browser doesn't support embedded videos.</video>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import md5 from "js-md5";
export default {
  name: "videoAdManagement",
  data() {
    return {
      //广告位置
      optionsPosition: [],
      //封面类型
      optionsAdType: [
        {
          value: "2",
          label: "视频(首页视频流专用)"
        },
        {
          value: "1",
          label: "图片"
        }
      ],
      //跳转类型
      optionsLinkType: [],
      search1: "",
      search2: "",
      tableData: [],
      currentPage1: 1,
      pageSize: 10,
      totalSize: 0,
      modifyEditorDialogVisible: false,
      addAdDialogVisible: false,
      //弹窗视频id
      inputID: "",
      //弹窗广告标题
      inputAdTitle: "",
      //弹窗封面类型
      inputAdType: "",
      //弹窗封面类型文字
      inputAdType_text: "",
      //弹窗广告位置
      inputPosition: "",
      //弹窗广告位置文字
      inputPosition_text: "",
      //弹窗上传图片地址
      dialogImageUrl: "",
      //图片预览
      dialogVisible: false,
      //上传视频文件地址
      uploadVedio: "",
      //上传图片文件地址
      uploadImg: "",
      //弹窗时间段
      inputTime: "",
      //弹窗跳转类型
      inputJumpType: "",
      //弹窗跳转链接
      inputJumpLink: "",
      //弹窗排序
      inputSort: "",
      //视频上传接口地址
      vedioUploadParth: "",
      //图片上传接口地址
      imgUploadParth: "",
      isShowBtn: true,
      initData: {},
      //编辑详情
      editorData: {},
      //选中行Id
      selectId: "",
      playDialogVisible: false,
      playUrl: "",
      fileList: [],
      // 权限管理
      permissions: [],
      permissions_obj: {}
    };
  },
  created() {
    //权限判断
    this.permissions = this.$store.state.permissions;
    let oneOff = false;
    this.permissions.forEach((item, index) => {
      if (item == -1) {
        oneOff = true;
      } else {
        this.permissions_obj["id_" + item] = item;
      }
    });
    if (oneOff) {
      this.permissions_obj.id_all = true;
    } else {
      this.permissions_obj.id_all = false;
    }
  },
  mounted() {
    this.getFileUploadParth();
    this.getOptionList();
  },
  methods: {
    // 分页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage1 = val;
      this.getAdList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAdList();
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除上传图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //添加
    addData() {
      this.inputID = "";
      this.inputAdType = "";
      this.inputAdType_text = "";
      this.inputPosition = "";
      this.inputPosition_text = "";
      this.inputAdTitle = "";
      this.uploadImg = "";
      this.uploadVedio = "";
      this.fileList = [];
      this.inputTime = [];
      this.inputJumpType = "";
      this.inputJumpLink = "";
      this.inputSort = "";
      this.addAdDialogVisible = true;
    },
    //状态开关监听
    changeSwitch(index, row) {
      let id = row.id;
      let status = row.status;
      if (row.status == 1) {
        row.status = 0;
      } else {
        row.status = 1;
      }
      this.$confirm("是否继续该操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.changeStatus(id, status);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消该操作"
          });
        });
    },
    //改变状态开关接口
    async changeStatus(id, status) {
      let parames = {
        handshake: "",
        data: {
          ad_id: id,
          status: status
        }
      };
      let res = await this.$axios.post(
        this.$api.adUpdate,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: "success"
        });
        this.getAdList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //编辑
    handleEdit(index, row) {
      this.inputID = "";
      this.inputAdType = "";
      this.inputAdType_text = "";
      this.inputPosition = "";
      this.inputPosition_text = "";
      this.inputAdTitle = "";
      this.uploadImg = "";
      this.uploadVedio = "";
      this.fileList = [];
      this.inputTime = [];
      this.inputJumpType = "";
      this.inputJumpLink = "";
      this.modifyEditorDialogVisible = true;
      this.selectId = row.id;
      this.getEditorData();
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("是否继续该操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteMethod(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除接口
    async deleteMethod(id) {
      let parames = {
        handshake: "",
        data: {
          ad_id: id
        }
      };
      let res = await this.$axios.post(
        this.$api.adDelete,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: "success"
        });
        this.getAdList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //提交修改
    async submitModifyEditor() {
      if (!this.inputAdTitle) {
        this.$message({
          message: "请填写广告标题",
          type: "warning"
        });
        return;
      }
      // if (!this.inputTime && this.inputTime.length < 1) {
      //   this.$message({
      //     message: "请选择时间段",
      //     type: "warning"
      //   });
      //   return;
      // }
      if (!this.inputJumpType) {
        this.$message({
          message: "请选择跳转类型",
          type: "warning"
        });
        return;
      }
      if (
        (this.inputJumpType == "url://" || this.inputJumpType == "video://") &&
        !this.inputJumpLink
      ) {
        this.$message({
          message: "请填写链接或者视频id",
          type: "warning"
        });
        return;
      }
      let parames = {
        handshake: "",
        data: {
          ad_id: this.inputID,
          type: this.inputAdType,
          position: this.inputPosition,
          title: this.inputAdTitle,
          cover: this.uploadImg,
          prefix: this.inputJumpType,
          url: this.inputJumpLink,
          play: this.uploadVedio,
          // start_time:
          //   this.inputTime && this.inputTime.length > 0
          //     ? this.inputTime[0]
          //     : "",
          // end_time:
          //   this.inputTime && this.inputTime.length > 1
          //     ? this.inputTime[1]
          //     : "",
          sort: this.inputSort
        }
      };
      let res = await this.$axios.post(
        this.$api.adSave,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: "success"
        });
        this.modifyEditorDialogVisible = false;
        this.getAdList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //取消提交
    cancelModifyEditor() {
      this.modifyEditorDialogVisible = false;
    },
    //图片上传成功
    imgUploadSuccess(response, file, fileList) {
      this.uploadImg = response.result.file_path;
    },
    // 视频上传成功
    uploadSuccess(response, file, fileList) {
      this.uploadVedio = response.result.file_path;
    },
    //获取文件上传地址
    async getFileUploadParth() {
      let parames = {
        handshake: "",
        data: {}
      };
      let res = await this.$axios.post(
        this.$api.uploadGet_domain,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        let timestamp = parseInt(new Date().getTime() / 1000);
        let platform = "P";
        let secret = "Z6Kbz8hpT9VtGmcu";
        let sign = md5(platform + timestamp + secret).toUpperCase();
        // console.log(sign);
        this.vedioUploadParth =
          res.data.url +
          "?dir=vd&platform=P&timestamp=" +
          timestamp +
          "&sign=" +
          sign;
        this.imgUploadParth =
          res.data.url +
          "?dir=ad&platform=P&timestamp=" +
          timestamp +
          "&sign=" +
          sign;
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //获取初始化广告列表
    async getAdList() {
      let parames = {
        handshake: "",
        data: {
          page: this.currentPage1,
          page_size: this.pageSize
        }
      };
      let res = await this.$axios.post(
        this.$api.adLists,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.initData = res.data;
        this.initData.data.forEach((item, index) => {
          if (item.type == 1) {
            item.type_text = "图片";
          } else if (item.type == 2) {
            item.type_text = "视频";
          }
          let imgArr = [];
          imgArr.push(item.cover);
          item.srcList = imgArr;
          this.optionsPosition.forEach((it, ind) => {
            if (item.position == it.value) {
              item.position_text = it.label;
            }
          });
        });
        this.totalSize = this.initData.total;
        this.tableData = this.initData.data;
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //获取广告下拉框内容
    async getOptionList() {
      let parames = {
        handshake: "",
        data: {}
      };
      let res = await this.$axios.post(
        this.$api.adType,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        let data = res.data;
        Object.keys(data.position).forEach((item, indedx) => {
          let obj = {};
          obj.value = item;
          obj.label = data.position[item];
          this.optionsPosition.push(obj);
        });
        Object.keys(data.type).forEach((item, indedx) => {
          let obj = {};
          obj.value = item;
          obj.label = data.type[item];
          this.optionsLinkType.push(obj);
        });
        this.getAdList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //提交添加
    async submitAdd() {
      if (!this.inputAdType) {
        this.$message({
          message: "请选择封面类型",
          type: "warning"
        });
        return;
      }
      if (!this.inputPosition) {
        this.$message({
          message: "请选择广告位置",
          type: "warning"
        });
        return;
      }
      if (!this.inputAdTitle) {
        this.$message({
          message: "请填写广告标题",
          type: "warning"
        });
        return;
      }
      if (!this.uploadImg) {
        this.$message({
          message: "请上传广告图片",
          type: "warning"
        });
        return;
      }
      if (this.inputAdType == 2 && !this.uploadVedio) {
        this.$message({
          message: "请上传视频",
          type: "warning"
        });
        return;
      }
      // if (!this.inputTime && this.inputTime.length < 1) {
      //   this.$message({
      //     message: "请选择时间段",
      //     type: "warning"
      //   });
      //   return;
      // }
      if (!this.inputJumpType) {
        this.$message({
          message: "请选择跳转类型",
          type: "warning"
        });
        return;
      }
      if (
        (this.inputJumpType == "url://" || this.inputJumpType == "video://") &&
        !this.inputJumpLink
      ) {
        this.$message({
          message: "请填写链接或者视频id",
          type: "warning"
        });
        return;
      }

      let parames = {
        handshake: "",
        data: {
          // ad_id:"",
          type: this.inputAdType,
          position: this.inputPosition,
          title: this.inputAdTitle,
          cover: this.uploadImg,
          prefix: this.inputJumpType,
          url: this.inputJumpLink,
          play: this.uploadVedio,
          // start_time:
          //   this.inputTime && this.inputTime.length > 0
          //     ? this.inputTime[0]
          //     : "",
          // end_time:
          //   this.inputTime && this.inputTime.length > 1
          //     ? this.inputTime[1]
          //     : "",
          sort: this.inputSort
        }
      };
      let res = await this.$axios.post(
        this.$api.adSave,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: "success"
        });
        this.addAdDialogVisible = false;
        this.getAdList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    cancelAdd() {
      this.addAdDialogVisible = false;
    },
    //获取编辑行信息
    async getEditorData() {
      let parames = {
        handshake: "",
        data: {
          ad_id: this.selectId
        }
      };
      let res = await this.$axios.post(
        this.$api.adDetail,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.editorData = res.data;
        this.inputID = this.editorData.id;
        this.inputAdType = this.editorData.type;
        // alert(this.inputAdType);
        this.optionsAdType.forEach((item, index) => {
          if (this.inputAdType == item.value) {
            this.inputAdType_text = item.label;
          }
        });
        this.inputPosition = this.editorData.position;
        this.optionsPosition.forEach((item, index) => {
          if (this.inputPosition == item.value) {
            this.inputPosition_text = item.label;
          }
        });
        this.inputAdTitle = this.editorData.title;
        let arr = [];
        arr.push(this.editorData.start_time);
        arr.push(this.editorData.end_time);
        this.inputTime = arr;
        this.inputJumpType = this.editorData.prefix;
        this.inputJumpLink = this.editorData.url;
        this.inputSort = this.editorData.sort;
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //播放
    handlePlay(index, row) {
      console.log(row.play);
      this.playDialogVisible = true;
      this.playUrl = row.play;
    }
  }
};
</script>
<style scoped>
h3 {
  padding: 0.2rem;
  color: #3c763d;
}
.search {
  display: flex;
  margin-top: 0.2rem;
  padding-left: 0.2rem;
  width: 100%;
  flex-wrap: wrap;
}
.el-input {
  width: 2.5rem;
}
label {
  width: 0.83rem;
  height: 0.4rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  font-size: 14px;
}
.cond {
  display: flex;
  margin-right: 0.4rem;
  margin-bottom: 0.1rem;
}
.search .el-select >>> .el-input__inner {
  border-left: none;
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
.search .el-select {
  width: 1.67rem;
}
.opration {
  margin-top: 0.2rem;
  padding-left: 0.2rem;
}
.page {
  margin-top: 0.2rem;
  display: flex;
  justify-content: center;
}
.list {
  margin-top: 0.2rem;
  padding: 0 0.1rem;
  font-size: 0.12rem;
}
.dialogBtn {
  display: flex;
  justify-content: center;
  margin-top: 0.3rem;
}
.row {
  margin-bottom: 0.1rem;
  display: flex;
  align-items: center;
}
.row span {
  width: 1rem;
  display: block;
}
</style>